package com.bw.lib_net.interceptor

import com.bw.lib_net.RetrofitManager
import com.bw.lib_net.TokenApi
import com.ostrich.lib_net.bus.LiveDataBus
import com.tencent.mmkv.MMKV
import okhttp3.Interceptor
import okhttp3.Response

/**
 * @Author : ZhouZiYao
 * @Time : On 2023/11/17 13:33
 * @Description :
 */
class TokenInterceptor:Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {

        val request = chain.request() //请求
        var response: Response? = null //响应

        //获得登录成功存储的token
        MMKV.defaultMMKV().encode(ConstantValue.TOKEN,"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJ6enkiLCJleHAiOjE3MDEzOTMwMTV9.GXpv8olPqhk7ZKbpaDknoUOV1z6uoP26bHz_iRfoxQw")

        //获得登录成功从存储的token
        val token = MMKV.defaultMMKV().decodeString(ConstantValue.TOKEN)

        response = if (token == null || token.isEmpty()){
            chain.proceed(request)//执行原来的request
        }else{
            val newRequest = chain.request().newBuilder().addHeader("token", token).build()
            chain.proceed(newRequest)//执行带有token的request
        }

        //判断响应码
        when(response?.code()){
            401 -> {
                //token过期:手动刷新重新登陆/自动刷新发起网络请求
                //方案yi:手动刷新重新登陆
                LiveDataBus.with<Int>(ConstantValue.NET_STATE).postValue(401)

                //方案er:自动刷新发起请求，无感
                val username = MMKV.defaultMMKV().decodeString(ConstantValue.USERNAME)
                val password = MMKV.defaultMMKV().decodeString(ConstantValue.PASSWORD)
                if (username?.isNotEmpty()!! && password?.isNotEmpty()!!){
                    val tokenApi = RetrofitManager.instance.createService(TokenApi::class.java)
                    val execute = tokenApi.refreshToken(username, password).execute()//同步发起请求
                    if (execute.isSuccessful){
                        val body = execute.body()
                        if (body != null){
                            //新的token更新到mmkv
                            val userEntity = body.data
                            MMKV.defaultMMKV().encode(ConstantValue.TOKEN, userEntity.token)
                            //带上新的token发起请求
                            val newRequest = chain.request().newBuilder().addHeader("token", token).build()
                            response = chain.proceed(newRequest)
                        }
                    }
                }

            }
            403 -> {
                //token失效
                LiveDataBus.with<Int>(ConstantValue.NET_STATE).postValue(403)
            }
            404 -> {
                //请求错误
                LiveDataBus.with<Int>(ConstantValue.NET_STATE).postValue(404)
            }
            500 -> {
                //服务器错误
                LiveDataBus.with<Int>(ConstantValue.NET_STATE).postValue(500)
            }
        }
        return response!!
    }
}